const express = require('express');
const https = require('https');
const http = require('http');
const WebSocket = require('ws');
const path = require('path');
const fs = require('fs');

const app = express();

// SSL证书配置
const options = {
    key: fs.readFileSync('cert/server.key'),
    cert: fs.readFileSync('cert/server.pem')
};

// 创建HTTPS服务器
const server = https.createServer(options, app);
const wss = new WebSocket.Server({ server });

// 静态文件服务
app.use(express.static(path.join(__dirname, 'public')));

const clients = new Set();

wss.on('connection', function connection(ws) {
    clients.add(ws);
    
    ws.on('message', function incoming(message) {
        // 确保消息是字符串
        const messageString = message.toString();
        
        // 广播消息给其他客户端
        clients.forEach(client => {
            if (client !== ws && client.readyState === WebSocket.OPEN) {
                client.send(messageString);
            }
        });
    });
    
    ws.on('close', () => {
        clients.delete(ws);
    });
});

const PORT = process.env.PORT || 443; // HTTPS默认端口
server.listen(PORT, () => {
    console.log(`HTTPS服务器运行在 https://127.0.0.1:${PORT}`);
});